import { type Message, getMessageReceiveList } from "@/api/message";
import type { PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted } from "vue";
import { DictTag } from "@/components/ReDict";
import { useRouter } from "vue-router";

export function userMessage() {
  const form = reactive<Message>({
    current: 1,
    size: 20
  });
  const router = useRouter();
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1
  });
  const columns: TableColumnList = [
    {
      label: "标题",
      prop: "title"
    },
    {
      label: "发送时间",
      prop: "sendTime"
    },
    {
      label: "发送人",
      prop: "sender"
    },
    {
      label: "状态",
      prop: "isRead",
      cellRenderer: ({ row, props }) => (
        <DictTag size={props.size} value={row.isRead} code="Message_Status" />
      )
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    form.size = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    form.current = val;
    onSearch();
  }

  function onSearch() {
    loading.value = true;
    getMessageReceiveList(form)
      .then(data => {
        dataList.value = data.records;
        pagination.total = data.total;
        pagination.pageSize = data.size;
        pagination.currentPage = data.current;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  const resetForm = (formEl: any) => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function viewMessage(id: string) {
    router.push({ name: "ViewMessage", query: { id: id } }).then(() => {
      onSearch();
    });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    viewMessage,
    handleSizeChange,
    handleCurrentChange
  };
}
